using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Avalonia;
using Avalonia.Media;

namespace JGSY.AI.DesktopUI.Services;

/// <summary>
/// 主题管理服务实现
/// </summary>
public class ThemeService : IThemeService
{
    private string _currentTheme = "PurpleGradient"; // 设置为紫色渐变主题
    private readonly List<ThemeInfo> _availableThemes;
    private readonly Dictionary<string, CustomThemeConfig> _customThemes;
    private readonly string _configDirectory;
    private readonly string _configFilePath;

    public string CurrentTheme => _currentTheme;

    public event EventHandler<string>? ThemeChanged;

    public ThemeService()
    {
        // 设置配置文件路径 - 优先使用应用程序目录下的配置文件
        var appDirectory = AppContext.BaseDirectory;
        var localConfigPath = Path.Combine(appDirectory, "Config", "theme-config.json");
        
        // 如果应用程序目录中存在配置文件，则使用它，否则使用AppData中的配置
        if (File.Exists(localConfigPath))
        {
            _configDirectory = Path.Combine(appDirectory, "Config");
            _configFilePath = localConfigPath;
            System.Diagnostics.Debug.WriteLine($"使用本地配置文件: {_configFilePath}");
        }
        else
        {
            _configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "JGSY.AI");
            _configFilePath = Path.Combine(_configDirectory, "theme-config.json");
            System.Diagnostics.Debug.WriteLine($"使用AppData配置文件: {_configFilePath}");
        }
        
        _customThemes = new Dictionary<string, CustomThemeConfig>();
        
        // 初始化内置主题 - 扩展到十种
        _availableThemes = new List<ThemeInfo>
        {
            new() { Name = "Ocean", DisplayName = "� 海洋蓝", Description = "清新自然的海洋主题" },
            new() { Name = "ModernBlue", DisplayName = "💙 现代蓝色", Description = "专业大气的蓝色渐变主题" },
            new() { Name = "PurpleGradient", DisplayName = "💜 紫色渐变", Description = "优雅时尚的紫色主题" },
            new() { Name = "DarkPro", DisplayName = "🌙 专业深色", Description = "高端专业的深色主题" },
            new() { Name = "CyberGreen", DisplayName = "🌿 科技绿色", Description = "未来科技感的绿色主题" },
            new() { Name = "SunsetOrange", DisplayName = "🧡 落日橙", Description = "温暖活力的橙色主题" },
            new() { Name = "RoseGold", DisplayName = "🌹 玫瑰金", Description = "奢华典雅的玫瑰金主题" },
            new() { Name = "MidnightBlue", DisplayName = "🌌 午夜蓝", Description = "深邃神秘的午夜蓝主题" },
            new() { Name = "ForestGreen", DisplayName = "🌲 森林绿", Description = "自然清新的森林绿主题" },
            new() { Name = "Light", DisplayName = "☀️ 简洁浅色", Description = "简洁明亮的浅色主题" }
        };

        // 确保配置目录存在
        Directory.CreateDirectory(_configDirectory);
        
        // 加载配置
        LoadConfiguration();
    }

    public IEnumerable<ThemeInfo> GetAvailableThemes()
    {
        var allThemes = new List<ThemeInfo>(_availableThemes);
        
        // 添加自定义主题
        foreach (var customTheme in _customThemes.Values)
        {
            allThemes.Add(new ThemeInfo
            {
                Name = customTheme.Name,
                DisplayName = customTheme.DisplayName,
                Description = customTheme.Description,
                IsCustom = true
            });
        }
        
        return allThemes;
    }

    public void ApplyTheme(string themeName)
    {
        if (Application.Current == null) return;

        var app = Application.Current;
        app.Resources.Clear();

        // 应用主题
        switch (themeName)
        {
            case "Ocean":
                LoadOceanTheme(app);
                break;
            case "ModernBlue":
                LoadModernBlueTheme(app);
                break;
            case "PurpleGradient":
                LoadPurpleGradientTheme(app);
                break;
            case "DarkPro":
                LoadDarkProTheme(app);
                break;
            case "CyberGreen":
                LoadCyberGreenTheme(app);
                break;
            case "SunsetOrange":
                LoadSunsetOrangeTheme(app);
                break;
            case "RoseGold":
                LoadRoseGoldTheme(app);
                break;
            case "MidnightBlue":
                LoadMidnightBlueTheme(app);
                break;
            case "ForestGreen":
                LoadForestGreenTheme(app);
                break;
            case "Light":
                LoadLightTheme(app);
                break;
            default:
                // 检查是否是自定义主题
                if (_customThemes.TryGetValue(themeName, out var customTheme))
                {
                    LoadCustomThemeColors(app, customTheme.Colors);
                }
                else
                {
                    LoadModernBlueTheme(app);
                }
                break;
        }

        _currentTheme = themeName;
        ThemeChanged?.Invoke(this, themeName);
        
        // 保存当前主题设置
        SaveCurrentTheme();
    }

    public void SwitchToNextTheme()
    {
        var themes = new[] { "Ocean", "ModernBlue", "PurpleGradient", "DarkPro", "CyberGreen", 
                           "SunsetOrange", "RoseGold", "MidnightBlue", "ForestGreen", "Light" };
        var currentIndex = Array.IndexOf(themes, _currentTheme);
        var nextIndex = (currentIndex + 1) % themes.Length;
        ApplyTheme(themes[nextIndex]);
    }

    public void LoadCustomTheme(CustomThemeConfig themeConfig)
    {
        _customThemes[themeConfig.Name] = themeConfig;
        SaveConfiguration();
    }

    public void SaveCurrentTheme()
    {
        SaveConfiguration();
    }

    private void LoadConfiguration()
    {
        try
        {
            if (File.Exists(_configFilePath))
            {
                System.Diagnostics.Debug.WriteLine($"开始加载主题配置: {_configFilePath}");
                var json = File.ReadAllText(_configFilePath);
                var config = JsonSerializer.Deserialize<ThemeConfiguration>(json);
                
                if (config != null)
                {
                    _currentTheme = config.CurrentTheme ?? "PurpleGradient"; // 使用紫色渐变主题作为默认
                    System.Diagnostics.Debug.WriteLine($"加载主题配置成功，当前主题: {_currentTheme}");
                    
                    if (config.CustomThemes != null)
                    {
                        foreach (var theme in config.CustomThemes)
                        {
                            _customThemes[theme.Name] = theme;
                        }
                        System.Diagnostics.Debug.WriteLine($"加载了 {config.CustomThemes.Count} 个自定义主题");
                    }
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"配置文件不存在: {_configFilePath}，将使用默认设置");
                _currentTheme = "PurpleGradient"; // 使用紫色渐变主题作为默认
            }
        }
        catch (Exception ex)
        {
            // 配置文件损坏时使用默认设置
            System.Diagnostics.Debug.WriteLine($"Failed to load theme configuration: {ex.Message}");
            _currentTheme = "PurpleGradient"; // 使用紫色渐变主题作为默认
        }
    }

    private void SaveConfiguration()
    {
        try
        {
            // 确保目录存在
            if (!Directory.Exists(_configDirectory))
            {
                Directory.CreateDirectory(_configDirectory);
            }
            
            var config = new ThemeConfiguration
            {
                CurrentTheme = _currentTheme,
                CustomThemes = new List<CustomThemeConfig>(_customThemes.Values)
            };

            var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(_configFilePath, json);
            
            System.Diagnostics.Debug.WriteLine($"主题配置已保存到: {_configFilePath}");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Failed to save theme configuration: {ex.Message}");
        }
    }

    private void LoadCustomThemeColors(Application app, ThemeColors colors)
    {
        // 处理渐变背景
        if (!string.IsNullOrEmpty(colors.WindowGradientStart) && !string.IsNullOrEmpty(colors.WindowGradientEnd))
        {
            var windowGradient = new LinearGradientBrush
            {
                StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
                EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
                GradientStops = new GradientStops
                {
                    new GradientStop { Color = Color.Parse(colors.WindowGradientStart), Offset = 0 },
                    new GradientStop { Color = Color.Parse(colors.WindowGradientEnd), Offset = 1 }
                }
            };
            app.Resources["WindowBackground"] = windowGradient;
            app.Resources["ContentBackground"] = windowGradient;
        }
        else
        {
            app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse(colors.WindowBackground));
            app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse(colors.ContentBackground));
        }

        // 处理标题栏渐变
        if (!string.IsNullOrEmpty(colors.TitleBarGradientStart) && !string.IsNullOrEmpty(colors.TitleBarGradientEnd))
        {
            var titleBarGradient = new LinearGradientBrush
            {
                StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
                EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
                GradientStops = new GradientStops
                {
                    new GradientStop { Color = Color.Parse(colors.TitleBarGradientStart), Offset = 0 },
                    new GradientStop { Color = Color.Parse(colors.TitleBarGradientEnd), Offset = 1 }
                }
            };
            app.Resources["TitleBarBackground"] = titleBarGradient;
        }
        else
        {
            app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse(colors.TitleBarBackground));
        }

        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse(colors.TitleBarBorder));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Color.Parse(colors.TitleBarForeground));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse(colors.ContentForeground));
    }

    #region 内置主题实现
    private void LoadModernBlueTheme(Application app)
    {
        var titleBarGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#667eea"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#764ba2"), Offset = 1 }
            }
        };

        var windowGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#f7f7f7"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#e8e8e8"), Offset = 1 }
            }
        };

        app.Resources["WindowBackground"] = windowGradient;
        app.Resources["TitleBarBackground"] = titleBarGradient;
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#5a67d8"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = windowGradient;
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#2d3748"));
    }

    private void LoadPurpleGradientTheme(Application app)
    {
        var titleBarGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#8e2de2"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#4a00e0"), Offset = 1 }
            }
        };

        var windowGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#faf5ff"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#f3e8ff"), Offset = 1 }
            }
        };

        app.Resources["WindowBackground"] = windowGradient;
        app.Resources["TitleBarBackground"] = titleBarGradient;
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#7c3aed"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = windowGradient;
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#581c87"));
    }

    private void LoadDarkProTheme(Application app)
    {
        var titleBarGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#232526"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#414345"), Offset = 1 }
            }
        };

        var windowGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#1a202c"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#2d3748"), Offset = 1 }
            }
        };

        app.Resources["WindowBackground"] = windowGradient;
        app.Resources["TitleBarBackground"] = titleBarGradient;
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#4a5568"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Color.Parse("#e2e8f0"));
        app.Resources["ContentBackground"] = windowGradient;
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#e2e8f0"));
    }

    private void LoadCyberGreenTheme(Application app)
    {
        var titleBarGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#11998e"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#38ef7d"), Offset = 1 }
            }
        };

        var windowGradient = new LinearGradientBrush
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
            GradientStops = new GradientStops
            {
                new GradientStop { Color = Color.Parse("#0f1419"), Offset = 0 },
                new GradientStop { Color = Color.Parse("#1a2332"), Offset = 1 }
            }
        };

        app.Resources["WindowBackground"] = windowGradient;
        app.Resources["TitleBarBackground"] = titleBarGradient;
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#2dd4bf"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = windowGradient;
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#10b981"));
    }

    private void LoadOceanTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#F0F8FF"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#1E90FF"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#4169E1"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#F0F8FF"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#2E8B57"));
    }

    private void LoadDarkTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#2D2D30"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#3E3E42"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#1E1E1E"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#2D2D30"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Colors.White);
    }

    private void LoadLightTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Colors.White);
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#F5F5F5"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#E0E0E0"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Color.Parse("#333333"));
        app.Resources["ContentBackground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#333333"));
        
        // 设置全局字体为微软雅黑
        app.Resources["DefaultFontFamily"] = new FontFamily("Microsoft YaHei");
        
        // 应用字体到各个控件
        app.Resources["TextBlock/FontFamily"] = new FontFamily("Microsoft YaHei");
        app.Resources["TextBox/FontFamily"] = new FontFamily("Microsoft YaHei");
        app.Resources["Button/FontFamily"] = new FontFamily("Microsoft YaHei");
        app.Resources["ComboBox/FontFamily"] = new FontFamily("Microsoft YaHei");
        app.Resources["CheckBox/FontFamily"] = new FontFamily("Microsoft YaHei");
        app.Resources["RadioButton/FontFamily"] = new FontFamily("Microsoft YaHei");
    }

    private void LoadPurpleTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#F3E5F5"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#9C27B0"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#7B1FA2"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#F3E5F5"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#4A148C"));
    }

    private void LoadSunsetOrangeTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#FFF3E0"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#FF9800"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#F57C00"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#FFF3E0"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#E65100"));
        app.Resources["CardBackground"] = new SolidColorBrush(Color.Parse("#FFCC80"));
        app.Resources["CardBorder"] = new SolidColorBrush(Color.Parse("#FFB74D"));
    }

    private void LoadRoseGoldTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#FCE4EC"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#E91E63"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#C2185B"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#FCE4EC"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#880E4F"));
        app.Resources["CardBackground"] = new SolidColorBrush(Color.Parse("#F8BBD9"));
        app.Resources["CardBorder"] = new SolidColorBrush(Color.Parse("#F48FB1"));
    }

    private void LoadMidnightBlueTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#0D1B2A"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#1B263B"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#415A77"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#0D1B2A"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#E0E1DD"));
        app.Resources["CardBackground"] = new SolidColorBrush(Color.Parse("#1B263B"));
        app.Resources["CardBorder"] = new SolidColorBrush(Color.Parse("#415A77"));
    }

    private void LoadForestGreenTheme(Application app)
    {
        app.Resources["WindowBackground"] = new SolidColorBrush(Color.Parse("#E8F5E8"));
        app.Resources["TitleBarBackground"] = new SolidColorBrush(Color.Parse("#2E7D32"));
        app.Resources["TitleBarBorder"] = new SolidColorBrush(Color.Parse("#1B5E20"));
        app.Resources["TitleBarForeground"] = new SolidColorBrush(Colors.White);
        app.Resources["ContentBackground"] = new SolidColorBrush(Color.Parse("#E8F5E8"));
        app.Resources["ContentForeground"] = new SolidColorBrush(Color.Parse("#1B5E20"));
        app.Resources["CardBackground"] = new SolidColorBrush(Color.Parse("#C8E6C9"));
        app.Resources["CardBorder"] = new SolidColorBrush(Color.Parse("#A5D6A7"));
    }
    #endregion
}

/// <summary>
/// 主题配置文件结构
/// </summary>
internal class ThemeConfiguration
{
    public string CurrentTheme { get; set; } = "ModernBlue";
    public List<CustomThemeConfig> CustomThemes { get; set; } = new();
}
